package com.acooly.module.openapi.client.provider.alipay;

import static com.acooly.module.openapi.client.provider.alipay.OpenAPIClientAlipayProperties.PREFIX;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import com.acooly.module.openapi.client.api.notify.ApiServiceClientServlet;
import com.acooly.module.openapi.client.provider.alipay.enums.AlipayServiceEnum;
import com.acooly.module.openapi.client.provider.alipay.notify.AlipayApiServiceClientServlet;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;


@EnableConfigurationProperties({OpenAPIClientAlipayProperties.class})
@ConditionalOnProperty(value = PREFIX + ".enable", matchIfMissing = true)
@ComponentScan
@Slf4j
public class OpenAPIClientAlipayConfigration {

	@Autowired
	private OpenAPIClientAlipayProperties openAPIClientAlipayProperties;

    @Bean("alipayClient")
    public AlipayClient AlipayHttpTransport() {
    	AlipayClient client = new DefaultAlipayClient(openAPIClientAlipayProperties.getGatewayUrl(), 
    			openAPIClientAlipayProperties.getAppId(), 
    			openAPIClientAlipayProperties.getPrivateKey(), 
    			AlipayConstants.FORMAT, 
    			AlipayConstants.CHARSET, 
    			openAPIClientAlipayProperties.getPublicKey(), 
    			AlipayConstants.SIGN_TYPE);
    	log.info("init alipay client bean");
        return client;
    }

    /**
     * 支付宝SDK-servlet注册
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean alipayApiServiceClientServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        AlipayApiServiceClientServlet apiServiceClientServlet = new AlipayApiServiceClientServlet();
        bean.setServlet(apiServiceClientServlet);
        bean.addInitParameter(ApiServiceClientServlet.NOTIFY_DISPATCHER_BEAN_NAME_KEY, "alipayNotifyHandlerDispatcher");
        List<String> urlMappings = Lists.newArrayList();       //网关异步通知地址
        urlMappings.add("/gateway/notify/alipayNotify/" + AlipayServiceEnum.PAY_ALIPAY_TRADE_APP.getKey());//访问，可以添加多个
        bean.setUrlMappings(urlMappings);
        bean.setLoadOnStartup(3);
        log.info("init alipay servlet url:{}",urlMappings.toString());
        return bean;
    }
}
